package cn.sciento.hitoa.metrics;

import cn.sciento.hitoa.thread.ThreadStateBean;
import cn.sciento.hitoa.thread.ThreadStateBeanImpl;
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.binder.MeterBinder;
import io.micrometer.core.lang.NonNullApi;
import io.micrometer.core.lang.NonNullFields;

import java.util.Collections;

@NonNullApi
@NonNullFields
public class ThreadMetrics implements MeterBinder {
    private final Iterable<Tag> tags;

    private ThreadStateBean threadStateBean;

    public ThreadMetrics() {
        this(Collections.emptyList());
    }

    public ThreadMetrics(Iterable<Tag> tags) {
        this.threadStateBean = (ThreadStateBean) new ThreadStateBeanImpl();
        this.tags = tags;
    }

    public void bindTo(MeterRegistry registry) {
        Gauge.builder("jvm.thread.NEW.sum", this.threadStateBean, ThreadStateBean::getThreadStatusNEWCount)
                .tags(this.tags)
                .description("thread state NEW count")
                .register(registry);
        Gauge.builder("jvm.thread.RUNNABLE.sum", this.threadStateBean, ThreadStateBean::getThreadStatusRUNNABLECount)
                .tags(this.tags)
                .description("thread state RUNNABLE count")
                .register(registry);
        Gauge.builder("jvm.thread.BLOCKED.sum", this.threadStateBean, ThreadStateBean::getThreadStatusBLOCKEDCount)
                .tags(this.tags)
                .description("thread state BLOCKED count")
                .register(registry);
        Gauge.builder("jvm.thread.WAITING.sum", this.threadStateBean, ThreadStateBean::getThreadStatusWAITINGCount)
                .tags(this.tags)
                .description("thread state WAITING count")
                .register(registry);
        Gauge.builder("jvm.thread.TIMEDWAITING.sum", this.threadStateBean, ThreadStateBean::getThreadStatusTIMEDWAITINGCount)
                .tags(this.tags)
                .description("thread state TIMED_WAITING count")
                .register(registry);
        Gauge.builder("jvm.thread.TERMINATED.sum", this.threadStateBean, ThreadStateBean::getThreadStatusTERMINATEDCount)
                .tags(this.tags)
                .description("thread state TERMINATED count")
                .register(registry);
    }
}
